<template>
	<div class="delay-detail-tables">
		<!-- 标签页切换 -->
		<el-tabs v-model="activeTab" @tab-click="handleTabClick">
			<el-tab-pane label="开工延期" name="start">
				<div class="table-container">
					<!-- 延期程度筛选和操作按钮 -->
					<div class="delay-filters">
						<div class="filter-left">
							<el-radio-group v-model="startDelayRange" @change="loadStartDelayData">
								<el-radio-button :value="DelayRangeEnum.All">全部延期</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Light">轻微延期(1-3天)</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Medium">中等延期(4-7天)</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Severe">严重延期(7天以上)</el-radio-button>
							</el-radio-group>
						</div>
						<div class="filter-right">
							<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStartDelayCommand">
								<el-button type="primary" :icon="Download" :loading="exportLoading" size="small"> 导出 </el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item command="select" :disabled="startSelectData.length == 0">导出选中</el-dropdown-item>
										<el-dropdown-item command="current">导出本页</el-dropdown-item>
										<el-dropdown-item command="all">导出全部</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>

					<!-- 开工延期表格 -->
					<el-table 
						:data="startDelayData" 
						:loading="startLoading" 
						stripe 
						border 
						height="400" 
						class="delay-table" 
						@sort-change="handleStartSortChange"
						@selection-change="(val: any[]) => { startSelectData = val; }"
					>
						<el-table-column type="selection" width="40" align="center" />
						<el-table-column prop="ch" label="船号" min-width="120" sortable="custom" />
						<el-table-column prop="fd" label="分段" min-width="120" sortable="custom" />
						<el-table-column prop="className" label="分类" min-width="100" />
						<el-table-column prop="workAreaName" label="区域" min-width="120" />
						<el-table-column prop="team" label="劳务队" min-width="120" />
						<el-table-column prop="planStart" label="计划开工" min-width="120" sortable="custom">
							<template #default="{ row }">
								<span>{{ formatDate(row.planStart) }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="actualStart" label="实际开工" min-width="120">
							<template #default="{ row }">
								<span v-if="row.actualStart">{{ formatDate(row.actualStart) }}</span>
								<el-tag v-else type="warning" size="small">未开工</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="delayDays" label="延期天数" min-width="100" sortable="custom">
							<template #default="{ row }">
								<el-tag :type="getDelayTagType(row.delayDays)" size="small"> {{ row.delayDays }}天 </el-tag>
							</template>
						</el-table-column>
					</el-table>

					<!-- 分页 -->
					<div class="pagination-container">
						<el-pagination
							v-model:current-page="startPagination.page"
							v-model:page-size="startPagination.size"
							:total="startPagination.total"
							:page-sizes="[10, 20, 50, 100, 200]"
							layout="total, sizes, prev, pager, next, jumper"
							@size-change="loadStartDelayData"
							@current-change="loadStartDelayData"
						/>
					</div>
				</div>
			</el-tab-pane>

			<el-tab-pane label="完工延期" name="end">
				<div class="table-container">
					<!-- 延期程度筛选和操作按钮 -->
					<div class="delay-filters">
						<div class="filter-left">
							<el-radio-group v-model="endDelayRange" @change="loadEndDelayData">
								<el-radio-button :value="DelayRangeEnum.All">全部延期</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Light">轻微延期(1-3天)</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Medium">中等延期(4-7天)</el-radio-button>
								<el-radio-button :value="DelayRangeEnum.Severe">严重延期(7天以上)</el-radio-button>
							</el-radio-group>
						</div>
						<div class="filter-right">
							<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportEndDelayCommand">
								<el-button type="primary" :icon="Download" :loading="exportLoading" size="small"> 导出 </el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item command="select" :disabled="endSelectData.length == 0">导出选中</el-dropdown-item>
										<el-dropdown-item command="current">导出本页</el-dropdown-item>
										<el-dropdown-item command="all">导出全部</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>

					<!-- 完工延期表格 -->
					<el-table 
						:data="endDelayData" 
						:loading="endLoading" 
						stripe 
						border 
						height="400" 
						class="delay-table" 
						@sort-change="handleEndSortChange"
						@selection-change="(val: any[]) => { endSelectData = val; }"
					>
						<el-table-column type="selection" width="40" align="center" />
						<el-table-column prop="ch" label="船号" min-width="120" sortable="custom" />
						<el-table-column prop="fd" label="分段" min-width="120" sortable="custom" />
						<el-table-column prop="className" label="分类" min-width="100" />
						<el-table-column prop="workAreaName" label="区域" min-width="120" />
						<el-table-column prop="team" label="劳务队" min-width="120" />
						<el-table-column prop="planEnd" label="计划完工" min-width="120" sortable="custom">
							<template #default="{ row }">
								<span>{{ formatDate(row.planEnd) }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="actualEnd" label="实际完工" min-width="120">
							<template #default="{ row }">
								<span v-if="row.actualEnd">{{ formatDate(row.actualEnd) }}</span>
								<el-tag v-else type="warning" size="small">未完工</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="delayDays" label="延期天数" min-width="100" sortable="custom">
							<template #default="{ row }">
								<el-tag :type="getDelayTagType(row.delayDays)" size="small"> {{ row.delayDays }}天 </el-tag>
							</template>
						</el-table-column>
					</el-table>

					<!-- 分页 -->
					<div class="pagination-container">
						<el-pagination
							v-model:current-page="endPagination.page"
							v-model:page-size="endPagination.size"
							:total="endPagination.total"
							:page-sizes="[10, 20, 50, 100, 200]"
							layout="total, sizes, prev, pager, next, jumper"
							@size-change="loadEndDelayData"
							@current-change="loadEndDelayData"
						/>
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download } from '@element-plus/icons-vue';
import { downloadStreamFile } from '/@/utils/download';
import { usePlanViewApi, type PlanListInput, type PlanListItem, type PlanListOutput, DelayRangeEnum } from '/@/api/plans/planView';

const planViewApi = usePlanViewApi();

// 定义Props
interface Props {
	filterParams: any;
}

const props = defineProps<Props>();

// 定义事件
const emit = defineEmits(['loading-change']);

// 响应式数据
const activeTab = ref('start');
const startDelayRange = ref<DelayRangeEnum>(DelayRangeEnum.All);
const endDelayRange = ref<DelayRangeEnum>(DelayRangeEnum.All);

// 表格数据（PlanListItem已包含delayDays字段）
const startDelayData = ref<PlanListItem[]>([]);
const endDelayData = ref<PlanListItem[]>([]);

// 选中数据
const startSelectData = ref<any[]>([]);
const endSelectData = ref<any[]>([]);

// 加载状态
const startLoading = ref(false);
const endLoading = ref(false);
const exportLoading = ref(false);

// 分页配置
const startPagination = reactive({
	page: 1,
	size: 10,
	total: 0,
});

const endPagination = reactive({
	page: 1,
	size: 10,
	total: 0,
});

// 排序配置
const startSort = reactive({
	prop: '',
	order: '',
});

const endSort = reactive({
	prop: '',
	order: '',
});

// 移除：延期天数现在由后端计算并返回

// 处理标签页切换
const handleTabClick = (tab: any) => {
	if (tab.name === 'start') {
		loadStartDelayData();
	} else {
		loadEndDelayData();
	}
};

// 加载开工延期数据
const loadStartDelayData = async () => {
	try {
		startLoading.value = true;
		emit('loading-change', true);

		// 构建请求参数 - 使用新的统一接口
    const params: PlanListInput = {
        className: props.filterParams.className,
        workAreaId: props.filterParams.workAreaId,
        rangeStart: (props.filterParams as any).rangeStart,
        rangeEnd: (props.filterParams as any).rangeEnd,
        listType: 'delaystart', // 开工延期类型
        pageIndex: startPagination.page,
        pageSize: startPagination.size,
        delayRange: startDelayRange.value, // 延期范围筛选
    };

		console.log('发送开工延期查询参数(新接口):', params);
		const response = await planViewApi.getPlanLists(params);
		console.log('开工延期查询响应(新接口):', response);
		
		const result = response.data?.result as PlanListOutput;
		if (result) {
			// 直接使用后端返回的数据，不再前端计算延期天数
			startDelayData.value = result.items;
			startPagination.total = result.total;
		} else {
			startDelayData.value = [];
			startPagination.total = 0;
		}
	} catch (error) {
		console.error('加载开工延期数据失败:', error);
		ElMessage.error('加载开工延期数据失败');
		startDelayData.value = [];
		startPagination.total = 0;
	} finally {
		startLoading.value = false;
		emit('loading-change', false);
	}
};

// 加载完工延期数据
const loadEndDelayData = async () => {
	try {
		endLoading.value = true;
		emit('loading-change', true);

		// 构建请求参数 - 使用新的统一接口
    const params: PlanListInput = {
        className: props.filterParams.className,
        workAreaId: props.filterParams.workAreaId,
        rangeStart: (props.filterParams as any).rangeStart,
        rangeEnd: (props.filterParams as any).rangeEnd,
        listType: 'delayend', // 完工延期类型
        pageIndex: endPagination.page,
        pageSize: endPagination.size,
        delayRange: endDelayRange.value, // 延期范围筛选
    };

		console.log('发送完工延期查询参数(新接口):', params);
		const response = await planViewApi.getPlanLists(params);
		console.log('完工延期查询响应(新接口):', response);
		
		const result = response.data?.result as PlanListOutput;
		if (result) {
			// 直接使用后端返回的数据，不再前端计算延期天数
			endDelayData.value = result.items;
			endPagination.total = result.total;
		} else {
			endDelayData.value = [];
			endPagination.total = 0;
		}
	} catch (error) {
		console.error('加载完工延期数据失败:', error);
		ElMessage.error('加载完工延期数据失败');
		endDelayData.value = [];
		endPagination.total = 0;
	} finally {
		endLoading.value = false;
		emit('loading-change', false);
	}
};

// 处理开工延期排序（新接口暂时简化排序处理）
const handleStartSortChange = ({ prop, order }: any) => {
	startSort.prop = prop;
	startSort.order = order;
	// TODO: 新接口可能需要不同的排序参数格式
	console.log('开工延期排序:', { prop, order });
	loadStartDelayData();
};

// 处理完工延期排序（新接口暂时简化排序处理）
const handleEndSortChange = ({ prop, order }: any) => {
	endSort.prop = prop;
	endSort.order = order;
	// TODO: 新接口可能需要不同的排序参数格式
	console.log('完工延期排序:', { prop, order });
	loadEndDelayData();
};

// 处理查看详情
const handleViewDetail = (row: any) => {
	ElMessageBox.alert(
		`
    <div style="text-align: left;">
      <p><strong>船号：</strong>${row.ch}</p>
      <p><strong>分段：</strong>${row.fd}</p>
      <p><strong>分类：</strong>${row.className}</p>
      <p><strong>区域：</strong>${row.workArea}</p>
      <p><strong>劳务队：</strong>${row.team}</p>
      <p><strong>延期天数：</strong>${row.delay}天</p>
    </div>
    `,
		'延期详情',
		{
			dangerouslyUseHTMLString: true,
			confirmButtonText: '确定',
		}
	);
};

// 格式化日期
const formatDate = (date: string | null) => {
	if (!date) return '';
	return new Date(date).toLocaleDateString('zh-CN');
};

// 获取延期标签类型
const getDelayTagType = (delay: number) => {
	if (delay >= 1 && delay <= 3) return 'info';      // 1-3天：灰色
	if (delay >= 4 && delay <= 7) return 'warning';   // 4-7天：橙色
	if (delay > 7) return 'danger';                   // 7天以上：红色
	return 'info';  // 默认灰色
};

// 导出开工延期Excel - 使用新的统一导出接口
const exportStartDelayCommand = async (command: string) => {
	try {
		exportLoading.value = true;
		
		// 基础参数
    const baseParams: PlanListInput = {
        className: props.filterParams.className,
        workAreaId: props.filterParams.workAreaId,
        rangeStart: (props.filterParams as any).rangeStart,
        rangeEnd: (props.filterParams as any).rangeEnd,
        listType: 'delaystart',
        delayRange: startDelayRange.value, // 延期范围筛选
    };
		
		let params: PlanListInput;
		if (command === 'select') {
			// 导出选中 - 新接口需要其他方式处理选中项，暂时导出当前页
			ElMessage.warning('导出选中功能暂时不支持，将导出当前页数据');
			params = {
				...baseParams,
				pageIndex: startPagination.page,
				pageSize: startPagination.size
			};
		} else if (command === 'current') {
			// 导出本页
			params = {
				...baseParams,
				pageIndex: startPagination.page,
				pageSize: startPagination.size
			};
		} else if (command === 'all') {
			// 导出全部 - 不设置分页参数表示导出全部
			params = baseParams;
		}

		console.log('导出开工延期Excel参数(新接口):', params);
		const response = await planViewApi.exportPlanListsExcel(params);
		await downloadStreamFile(response);
	} catch (error) {
		console.error('导出开工延期Excel失败:', error);
		ElMessage.error('导出开工延期Excel失败');
	} finally {
		exportLoading.value = false;
	}
};

// 导出完工延期Excel - 使用新的统一导出接口
const exportEndDelayCommand = async (command: string) => {
	try {
		exportLoading.value = true;
		
		// 基础参数
    const baseParams: PlanListInput = {
        className: props.filterParams.className,
        workAreaId: props.filterParams.workAreaId,
        rangeStart: (props.filterParams as any).rangeStart,
        rangeEnd: (props.filterParams as any).rangeEnd,
        listType: 'delayend',
        delayRange: endDelayRange.value, // 延期范围筛选
    };
		
		let params: PlanListInput;
		if (command === 'select') {
			// 导出选中 - 新接口需要其他方式处理选中项，暂时导出当前页
			ElMessage.warning('导出选中功能暂时不支持，将导出当前页数据');
			params = {
				...baseParams,
				pageIndex: endPagination.page,
				pageSize: endPagination.size
			};
		} else if (command === 'current') {
			// 导出本页
			params = {
				...baseParams,
				pageIndex: endPagination.page,
				pageSize: endPagination.size
			};
		} else if (command === 'all') {
			// 导出全部 - 不设置分页参数表示导出全部
			params = baseParams;
		}

		console.log('导出完工延期Excel参数(新接口):', params);
		const response = await planViewApi.exportPlanListsExcel(params);
		await downloadStreamFile(response);
	} catch (error) {
		console.error('导出完工延期Excel失败:', error);
		ElMessage.error('导出完工延期Excel失败');
	} finally {
		exportLoading.value = false;
	}
};

// 监听筛选条件变化
watch(
	() => props.filterParams,
	(newParams) => {
		console.log('DelayDetailTables watch 触发, 新参数:', newParams);
		console.log('当前activeTab:', activeTab.value);
		if (activeTab.value === 'start') {
			console.log('调用 loadStartDelayData');
			loadStartDelayData();
		} else {
			console.log('调用 loadEndDelayData');
			loadEndDelayData();
		}
	},
	{ deep: true }
);

// 监听分页变化时重新加载数据（新接口支持后端分页）
watch(
	() => [startPagination.page, startPagination.size],
	() => {
		if (activeTab.value === 'start') {
			loadStartDelayData();
		}
	}
);
watch(
	() => [endPagination.page, endPagination.size],
	() => {
		if (activeTab.value === 'end') {
			loadEndDelayData();
		}
	}
);

// 组件挂载
onMounted(() => {
	loadStartDelayData();
});
</script>

<style lang="scss" scoped>
.delay-detail-tables {
	padding: 20px;

	.table-container {
		.delay-filters {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 16px;
			padding: 12px;
			background: var(--el-fill-color-extra-light) !important;
			border: 1px solid var(--el-border-color-lighter);
			border-radius: 6px;

			.filter-left {
				flex: 1;
				
				:deep(.el-radio-button__inner) {
					border-radius: 4px;
					margin-right: 8px;
					background: var(--el-bg-color) !important;
					border-color: var(--el-border-color) !important;
					color: var(--el-text-color-primary) !important;
					box-shadow: none !important;
				}
				
				:deep(.el-radio-button.is-active .el-radio-button__inner) {
					background: var(--el-color-primary) !important;
					border-color: var(--el-color-primary) !important;
					color: var(--el-color-white) !important;
				}
				
				:deep(.el-radio-button:hover .el-radio-button__inner) {
					border-color: var(--el-color-primary) !important;
				}
				
				:deep(.el-radio-button:first-child .el-radio-button__inner) {
					border-left: 1px solid var(--el-border-color) !important;
				}
			}

			.filter-right {
				margin-left: 16px;
			}
		}

		.delay-table {
			:deep(.el-table__header) {
				background: var(--el-fill-color-light);
			}

			:deep(.el-table__row) {
				&:hover {
					background: var(--el-fill-color-lighter);
				}
			}
		}

		.pagination-container {
			display: flex;
			justify-content: center;
			margin-top: 20px;
		}
	}

	:deep(.el-tabs__header) {
		margin-bottom: 0;
	}

	:deep(.el-tabs__content) {
		padding: 0;
	}

	:deep(.el-tab-pane) {
		background: var(--el-bg-color);
		border-radius: 6px;
	}
}

@media (max-width: 768px) {
	.delay-detail-tables {
		padding: 15px;

		.delay-filters {
			:deep(.el-radio-group) {
				display: flex;
				flex-wrap: wrap;
				gap: 8px;
			}

			:deep(.el-radio-button) {
				margin-bottom: 8px;
			}
		}

		.delay-table {
			:deep(.el-table__body-wrapper) {
				overflow-x: auto;
			}
		}
	}
}
</style>
